import { Button, Result } from 'antd';
import { Link } from 'umi';
import React from 'react';
import type { Route } from '@ant-design/pro-layout/es/typings';
import { useTranslation } from 'react-i18next';
import { useSelector } from '@@/plugin-dva/exports';
import type { ConnectState } from '@/models/connect';
import { getCurrentMenu } from '@/utils/getPageTitle';

const DefaultNoMatch: React.FC = () => {
  const { t } = useTranslation();
  return (
    <Result
      status={403}
      title="403"
      subTitle={t('notPermission')}
      extra={
        <Button type="primary">
          <Link to="/user/login">Go Login</Link>
        </Button>
      }
    />
  );
};

export type UriPermissionProps = {
  /**
   * 当前项目的路由表
   */
  route: Route;
  children: any;
};

/**
 * 验证路由权限
 * @param props
 * @constructor
 */
const RoutePermission: React.FC<UriPermissionProps> = (props) => {
  // 获取菜单数据
  const menuList = useSelector((state) => (state as ConnectState).global.menuList);
  // 菜单是否已加载
  const menuLoaded = useSelector((state) => (state as ConnectState).global.menuLoaded);
  const { children, route } = props;
  if (!menuLoaded || getCurrentMenu(menuList, route?.path)) {
    // 菜单未加载或当前访问的路由path与某个菜单匹配,则允许访问
    return children;
  }
  // 未授权禁止访问
  return <DefaultNoMatch />;
};

export default RoutePermission;
